<?php
/***
*
* Class: WechatController //微信交互控制器
* Author: Jason ZHENG
* Data: 2018-06-21
*
***/
namespace App\Http\Controllers;

use App\Service\DataReturnService as DRS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session; 
use App\Common\AliyunSms;
use App\Common\Base;
use App\Service\WeixinPayService;
use App\Validator\WechatValidator;
use App\Service\YoppayService;
use App\Service\YoppayUtils\Util\YopSignUtils;

class WechatController extends Controller
{
    /**
     * 实例化一个新的控制器实例。
     *
     * @return void
     */
    public function __construct()
    {
        
    }

    public function index()
    {
    	return "Wechat controller";
    }

    public function login(Request $request)
    {
        $postData  = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'openid'    => 'required|string', 
                                        'appid'     => 'required|string', 
                                        'userInfo'  => 'required'
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        $business = DB::table('business')->where('appid', $postData['appid'])->first();
        if(empty($business)){
            return DRS::returnError(1001,'该商家不存在或者没有绑定微信公众号！');
        }

        $fields = ['users.id','users.name','users.is_business', 'users.phone', 
                            'users.openid', 'users.unionid', 'users.state','user_info.age',
                            'user_info.age','user_info.sex','user_info.topimageurl'];

        $business_user = DB::table('users')
                            ->leftJoin('user_info', 'users.id', '=', 'user_info.user_id')
                            ->select($fields)
                            ->where('users.id', $business->business_id)
                            ->first();

        $user = DB::table('users')
                ->leftJoin('user_info', 'users.id', '=', 'user_info.user_id')
                ->select($fields)
                ->where('openid', $postData['openid'])
                ->first();

        if(empty($user))
        {            
            $userId = DB::table('users')
                    ->insertGetId([
                                    'system_id'     => $business_user->system_id,
                                    'name'          => $postData['userInfo']['nickName'], 
                                    'openid'        => $postData['openid'], 
                                    'password'      => '888888', 
                                    'business_id'   => $business->business_id,
                                    'createtime'    => date('Y-m-d H:i:s'),
                                ]);
            DB::table('user_info')
                ->insert([
                            'user_id'           => $userId, 
                            'name'              => $postData['userInfo']['nickName'], 
                            'topimageurl'       => $postData['userInfo']['avatarUrl']
                        ]);
            $user = DB::table('users')
                        ->leftJoin('user_info', 'users.id', '=', 'user_info.user_id')
                        ->select($fields)
                        ->where('users.id', $userId)
                        ->first();

        }

        Session::put('user',            (array)$user);
        Session::put('open_id',         $postData['openid']);
        Session::put('business',        (array)$business_user);
        
        return DRS::returnOk(['user' => (array)$user, 'business' => (array)$business_user ]);
    }

    public function login_by_code(Request $request)
    { 
        $postData  = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'business_id'   => 'required',
                                        'code'          => 'required|string', 
                                        'avatarUrl'     => 'required',
                                        'nickName'      => 'required',
                                        // 'gender'        => 'required',
                                        // 'country'       => 'required',
                                        // 'province'      => 'required',
                                        // 'city'          => 'required',
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors()->first());
        }

        $business = DB::table('business')->where('business_id',$postData['business_id'])->first();
        if(empty($business)){
            return DRS::returnError(1001,'该商家不存在！');
        }elseif($business->appid == null || $business->secret == null){
            return DRS::returnError(1001,'该商家没有绑定微信公众号！');
        }

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$business->appid.'&secret='.$business->secret.'&js_code='.$postData['code'].'&grant_type=authorization_code';
        
        $data = json_decode(file_get_contents($url),true);

        if(!isset($data['openid'])){
            return DRS::returnError(1002,'获取用户openid失败！');
        }
        
        $fields = ['users.id','users.system_id','users.name','users.is_business', 'users.phone', 
                    'users.openid', 'users.unionid', 'users.state','user_info.age',
                    'user_info.sex','user_info.topimageurl','user_info.country','user_info.province','user_info.city'];

        $business_user = DB::table('users')
                            ->leftJoin('user_info', 'users.id', '=', 'user_info.user_id')
                            ->select($fields)
                            ->where('users.id', $business->business_id)
                            ->first();

        $user = DB::table('users')
                ->leftJoin('user_info', 'users.id', '=', 'user_info.user_id')
                ->select($fields)
                ->where(['openid' => $data['openid'], 'business_id' => $postData['business_id']])
                ->first();

        $token = md5(time().$business->business_id);
        DB::beginTransaction(); 
        try {
            if(empty($user))
            {   
                       
                $userId = DB::table('users')
                        ->insertGetId([
                                        'name'          => $postData['nickName'], 
                                        'system_id'     => $business_user->system_id,
                                        'openid'        => $data['openid'], 
                                        'password'      => '888888', 
                                        'business_id'   => $postData['business_id'],
                                        'is_customer'   => 1,
                                        'createtime'    => date('Y-m-d H:i:s'),
                                        'source'        => 2
                                    ]); 
                DB::table('user_info')
                    ->insert([
                                'user_id'           => $userId, 
                                'name'              => $postData['nickName'], 
                                'topimageurl'       => $postData['avatarUrl'],
                                'sex'               => isset($postData['gender']) ? $postData['gender'] : 3,
                                'country'           => isset($postData['country']) ? $postData['country'] : null,
                                'province'          => isset($postData['province']) ?  $postData['province']: null,
                                'city'              => isset($postData['city']) ? $postData['city'] : null,
                            ]);

                
                DB::table('token')->where(['user_id' => $userId])->delete();
                DB::table('token')->insert(['token_value' => $token, 'user_id' => $userId, 'add_time' => date('Y-m-d H:i:s')]);
                $user = DB::table('users')
                            ->leftJoin('user_info', 'users.id', '=', 'user_info.user_id')
                            ->select($fields)
                            ->where('users.id', $userId)
                            ->first();

            }else{
                DB::table('token')->where(['user_id' => $user->id])->delete();
                DB::table('token')->insert(['token_value' => $token, 'user_id' => $user->id, 'add_time' => date('Y-m-d H:i:s')]);
            }
            DB::commit();

        }catch(\Exception $exception) {
                DB::rollBack();
                return DRS::returnError(1000,'插入数据库出错！');
        }

        Session::put('user',            (array)$user);
        Session::put('open_id',         $data['openid']);
        Session::put('business',        (array)$business_user);
        
        return DRS::returnOk(['token'=>$token,'user' => (array)$user, 'business' => (array)$business_user ]);
    }

    public function register(Request $request)
    { 
        $postData  = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'openid'        => 'required|string', 
                                        'phone'         => 'required',
                                        'code'          => 'required',
                                        'business_id'   => 'required'
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors()->first());
        }

        $openidUser = DB::table('users')->where(['openid'=>$postData['openid'], 'business_id' => $postData['business_id']])->first();
        if($openidUser == null){
            return DRS::returnError(1000,'该微信号还未注册！');
        }

        $phoneCode = DB::table('phone_code')->where(['phone'=>$postData['phone'],'code' => $postData['code'] ])->first();
        if($phoneCode == null){
            return DRS::returnError(1000,'验证码错误！');
        }elseif((strtotime(date('Y-m-d H:i:s')) - strtotime($phoneCode->createtime)) > 10*60){
            return DRS::returnError(1000,'验证码已失效！');
        }

        $phoneUser = DB::table('users')->where(['phone'=>$postData['phone'],'business_id' => $postData['business_id']])->first();

        DB::beginTransaction();
        try {
            // 判断手机注册用户是否已存在
            if($phoneUser == null || $openidUser->id == $phoneUser->id)
            {
                // 更新微信注册用户的手机信息
                DB::table('users')->where(['openid' => $postData['openid'],'business_id'=>$postData['business_id']])->update(['phone' => $postData['phone']]);
                // 判断是否已经是客户，否的话新增客户
                $customer = DB::table('customer')->where(['business_id' => $postData['business_id'], 'user_id'=> $openidUser->id])->first();
                if($customer == null){
                    $insertCustomer = [
                        'system_id'     => $openidUser->system_id,
                        'business_id'   => $postData['business_id'],
                        'user_id'       => $openidUser->id,
                        'createtime'    => date('Y-m-d H:i:s'),
                    ];
                    DB::table('customer')->insert($insertCustomer);
                }
                DB::commit();
                // 返回token
                $token = DB::table('token')->where(['user_id'=>$openidUser->id])->first();
                if($token == null){
                    DB::table('token')->insert(['token_value' => md5(time()), 'user_id' => $openidUser->id, 'add_time' => date('Y-m-d H:i:s')]);
                    $token = DB::table('token')->where(['user_id'=>$openidUser->id])->first();
                }
                return DRS::returnOK(['token' => $token->token_value],'绑定成功');
            }else{
                //把添加的优惠券换成手机用户的id
                $tickets = DB::table('ticket_user')->where(['user_id'=>$openidUser->id])->get();
                if($tickets != null){
                    foreach ($tickets as $ticket) {
                        DB::table('ticket_user')->where(['id'=>$ticket->id])->update(['user_id' => $phoneUser->id ]);
                    }
                }
                // 把购物车的商品换成手机用户的id
                $carts = DB::table('cart')->where(['user_id'=>$openidUser->id])->get();
                if($carts != null){
                    foreach ($carts as $cart) {
                        DB::table('cart')->where(['id'=>$cart->id])->update(['user_id' => $phoneUser->id ]);
                    }
                }
                // 更新手机用户的信息
                DB::table('users')->where(['id'=>$phoneUser->id])->update(['openid'=>$openidUser->openid,'name' =>  $openidUser->name,'is_customer' => 1,'source' =>2]);
                //检查是否为客户，否的话新增客户
                $customer = DB::table('customer')->where(['business_id' => $postData['business_id'], 'user_id'=> $phoneUser->id])->first();
                if($customer == null){
                    $insertCustomer = [
                        'system_id'     => $phoneUser->system_id,
                        'business_id'   => $postData['business_id'],
                        'user_id'       => $phoneUser->id,
                        'createtime'    => date('Y-m-d H:i:s'),
                    ];
                    DB::table('customer')->insert($insertCustomer);
                }
                //删除openid注册的新客户
                DB::table('users')->where(['id'=>$openidUser->id])->delete();
                // 更新user info表
                $user_info = DB::table('user_info')->where(['user_id'=>$openidUser->id])->first();
                $userInfoData = [
                    'name'          => $user_info->name,
                    'age'           => $user_info->age,
                    'sex'           => $user_info->sex,
                    'topimageurl'   => $user_info->topimageurl,
                    'country'       => $user_info->country,
                    'province'      => $user_info->province,
                    'city'          => $user_info->city,
                    'hometown'      => $user_info->hometown,
                    'residence'     => $user_info->residence,
                ];
                DB::table('user_info')->where(['user_id' => $phoneUser->id])->update($userInfoData);
                //删除open id注册进来的user info信息
                DB::table('user_info')->where(['user_id' => $openidUser->id])->delete();
                DB::commit();

                //产生token
                $token = DB::table('token')->where(['user_id'=>$phoneUser->id])->first();
                if($token == null){
                    DB::table('token')->insert(['token_value' => md5(time()), 'user_id' => $openidUser->id, 'add_time' => date('Y-m-d H:i:s')]);
                    $token = DB::table('token')->where(['user_id'=>$phoneUser->id])->first();
                }
                return DRS::returnOK(['token' => $token->token_value],'绑定成功');
            }

        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollback();
            return DRS::returnError(1000,'绑定错误', $e);
        }
        
    }

    public function sendSms(Request $req)
    {
        $code = rand(1000, 9999);
        $data = $req->post();
        $validator = Validator::make($data, 
                                    [
                                        'phone'    => 'required'
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        // if(! preg_match("/^1[34578]\d{9}$/", $data['phone']) ){
        //     return DRS::returnError(1000,'手机号码错误！',$data['phone']);
        // }

        $phoneCode = DB::table('phone_code')->where(['phone'=>$data['phone']])->first();
        if($phoneCode != null){
            DB::table('phone_code')->where(['phone'=>$data['phone']])->update(['code' => $code, 'createtime'=>date('Y-m-d H:i:s')]);
        }else{
            DB::table('phone_code')->insert(['phone'=>$data['phone'], 'code' => $code, 'createtime'=>date('Y-m-d H:i:s')]);
        }

        if( preg_match("/^1[34578]\d{9}$/", $data['phone']) ){
            // 中国手机号
            $aliyunSms = new AliyunSms();
            $aliyunSms->code_type($code);
            return $aliyunSms->setRecNum($data['phone']);
        }else{
            // 国外手机号
            $aliyunSms = new AliyunSms();
            $aliyunSms->code_type($code,'globalreg');
            return $aliyunSms->setRecNum($data['phone']);
        }

    }
    //发起支付
    public function pay(Request $request)
    { 
        $postData  = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                        'business_id'   => 'required|numeric',
                                        'openid'        => 'required|string', 
                                        'batchcode'     => 'required',
                                        'total_fee'     => 'required|numeric',
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        if($postData['total_fee'] == null || $postData['total_fee'] == 0 || $postData['total_fee'] < 0){
            return DRS::returnError(1001,'该订单不需要支付');
        }

        $userInfo = Base::getUserByToken($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];

        $businessQuery = DB::table('business')->where(['business_id' => $postData['business_id']])->first();
        $yeePayConfig = config('app.yeepay');
        if($businessQuery !== null){
            $appid              = isset($businessQuery->appid) ? $businessQuery->appid : null;
            $appKey             = isset($yeePayConfig['appKey']) ? $yeePayConfig['appKey'] : null;
            $parentMerchantNo   = isset($businessQuery->parentMerchantNo) ? $businessQuery->parentMerchantNo : null;
            $merchantNo         = isset($businessQuery->merchantNo) ? $businessQuery->merchantNo : null;
            $private_key        = isset($yeePayConfig['private_key']) ? $yeePayConfig['private_key'] : null;
            $yop_public_key     = isset($yeePayConfig['yop_public_key']) ? $yeePayConfig['yop_public_key'] : null;

            
            if($appid == ''){
                return DRS::returnError(1001,'该商户未绑定公众号appid！');
            }elseif($appKey == ''){
                return DRS::returnError(1001,'配置缺少系统商的易宝支付appKey！');
            }elseif($parentMerchantNo == ''){
                return DRS::returnError(1001,'该商户未绑定易宝支付总商户号parentMerchantNo！');
            }elseif($merchantNo == ''){
                return DRS::returnError(1001,'该商户未绑定易宝支付子商户号merchantNo!');
            }elseif($private_key == ''){
                return DRS::returnError(1001,'配置缺少系统商的易宝支付商户私钥private_key!');
            }elseif($yop_public_key == ''){
                return DRS::returnError(1001,'配置缺少系统商的易宝支付商户公钥yop_public_key!');
            }else{
                $yopData = [
                    'parentMerchantNo'  => $parentMerchantNo,
                    'merchantNo'        => $merchantNo,
                    'orderAmount'       => $postData['total_fee'],
                    'notifyUrl'         => config('app.url').'/api/miniapp/wechat/pay_notify',
                ];

                $yopParams = [
                    'private_key'   => $private_key,
                    'yop_public_key'=> $yop_public_key,
                    'payTool'       => 'MINI_PROGRAM',
                    'payType'       => 'WECHAT',
                    'userNo'        => $user['id'],
                    'userType'      => 'USER_ID',
                    'appId'         => $appid,
                    'openId'        => $postData['openid'],
                    'userIp'        => $_SERVER["REMOTE_ADDR"],
                    'version'       => '1.0'
                ];

                $order = DB::table('orders')
                        ->where([
                                    'batchcode' => $postData['batchcode'], 
                                    'user_id'   => $user['id'], 
                                    'state'     => 0
                                ])
                        ->first();
                if($order == null){
                    $unitOrderValidate = WechatValidator::wexinPayUnitOrderValidate($postData['batchcode'], $user['id'], $postData['total_fee']);
                    if($unitOrderValidate['code'] != '666'){
                        return $unitOrderValidate;
                    }
                    $unitOrder = $unitOrderValidate['data'];
                    $yopData['orderId'] = $unitOrder['pay_batchcode'];
                    
                    $return = YoppayService::yoppay($yopData, $yopParams);
                    
                    if($return['code'] == 'CAS00000'){
                        return $return['resultData'];
                    }else{
                        DRS::returnError(1001,'支付失败，请重试！', $return); 
                    }    
                    
                }else{
                    $orderValidate =  WechatValidator::wexinPayOrderValidate($order, $postData['total_fee']);
                    if($orderValidate['code'] != '666'){
                        return $orderValidate;
                    }
                    $yopData['orderId'] = $order->batchcode;
                    $return = YoppayService::yoppay($yopData, $yopParams);
                    if($return['code'] == 'CAS00000'){
                        return $return['resultData'];
                    }else{
                        DRS::returnError(1001,'支付失败，请重试！', $return); 
                    }  
                }
            }
        }else{
            return DRS::returnError(1001,'该商户不存在！', $businessQuery); 
        }

    }
    //支付成功回调函数
    public function pay_notify(Request $request)
    {   
        $yeePayConfig = config('app.yeepay');
        $source = $request->post();

        $data = $_REQUEST["response"]; 
        $callback = YopSignUtils::decrypt($data,$yeePayConfig['private_key'], $yeePayConfig['yop_public_key']);
        $callback = json_decode($callback, true);

        Base::yibaoLog(6,'pay_notify',$data,json_encode($callback));

        if($callback['status'] == 'SUCCESS')
        {
            $batchcode = $callback['orderId'];
            $orderQuery = DB::table('orders')->where(['batchcode' => $batchcode])->first();
            if($orderQuery == null){
                $unitOrder = DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->first();
                if($unitOrder == null){
                    return DRS::returnError(1001,'找不到该订单');
                }else{
                    $originOrder = DB::table('orders')->where(['batchcode' => $unitOrder->batchcode])->first();
                    //  如果有优惠券，先禁用
                    if($originOrder->coupon_id !== null){
                        DB::table('ticket_user')->where(['user_id'=>$originOrder->user_id, 'ticket_id' => $originOrder->coupon_id])->update(['state' => 1, 'update_date' => date('Y-m-d H:i:s')]);
                    }
                    // 改变一条分笔订单的状态
                    DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->update(['payment_status'=> 1, 'payment_time' => date('Y-m-d H:i:s'), 'transaction_id' => $callback['uniqueOrderNo'], 'pay_code' => 0, 'update_time' => date('Y-m-d H:i:s') ]);
                    // 增加一条商户的不可提现余额记录
                    // DB::table('merchant_currency')->insert(['user_id'=>$originOrder->business_id, 'unitOrderId' => $unitOrder->id, 'money'=>$callback['payAmount'],'batchcode' =>$batchcode ,'uniqueOrderNo'=>$callback['uniqueOrderNo'] ,'type' => 1, 'state'=>0,'createtime'=>date('Y-m-d H:i:s')]);
                    $unitOrders = DB::table('unit_order')->where(['batchcode' => $unitOrder->batchcode])->get();
                    $is_allpay = true;
                    foreach ($unitOrders as $key => $unitO) {
                        if($unitO->payment_status != 1){
                            $is_allpay = false;
                        }
                    }
                    // 如果分笔订单全付完
                    if($is_allpay == true)
                    {
                        // 改变总订单的状态
                        DB::table('orders')->where(['batchcode' => $unitOrder->batchcode])->update(['payment_status'=> 1, 'status' => 2, 'pay_time' => date('Y-m-d H:i:s'), 'uniqueOrderNo'=> $callback['uniqueOrderNo'], 'pay_code' => 0 ]);
                        // 改变总订单详情的状态
                        DB::table('orders_info')->where(['batchcode' => $unitOrder->batchcode])->update(['payment_status'=> 1,'status' => 2,'pay_batchode'=> $callback['uniqueOrderNo'], 'pay_reatetime' => date('Y-m-d H:i:s'), 'last_time' => date('Y-m-d H:i:s')]);
                        $orderInfos = DB::table('orders_info')->where(['batchcode' => $unitOrder->batchcode])->get();
                        foreach ($orderInfos as $orderInfo) {
                            // 更新每一件产品的状态为待发货
                            DB::table('product')->where(['id' => $orderInfo->product_id])->update(['product_state' => 10]);
                            // 如果商品是同步商品，则要发起分账请求并改变原商家订单的状态
                            YoppayService::updateOriginalOrder($orderInfo);
                        }
                            // 本商户提现金额里需要减去的金额（所有同步商品的同行价总和）
                            $sholdRemoveMoney = 0;
                            foreach ($orderInfos as $orderInfo) 
                            {
                                $product = DB::table('product')->where(['id' => $orderInfo->product_id])->first();
                                if($product->is_synchro == 1)
                                {
                                    $sourceProduct = DB::table('product')->where(['id' => $product->source_product_id])->first();
                                    $sholdRemoveMoney = $sholdRemoveMoney + $sourceProduct->peer_price;
                                }
                            }
                            // 增加一条商户的不可提现余额记录
                            DB::table('merchant_currency')->insert(['user_id'=>$orderQuery->business_id, 'orderId' => $orderQuery->id, 'money'=>round(($callback['payAmount']-$sholdRemoveMoney),2),'batchcode' =>$batchcode ,'uniqueOrderNo'=>$callback['uniqueOrderNo'] ,'type' => 1, 'state'=>0,'createtime'=>date('Y-m-d H:i:s')]);
                    }
                    $order_status = DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->first();

                }
            }else{
                // 如果有优惠券，先禁用
                if($orderQuery->coupon_id !== null){
                    DB::table('ticket_user')->where(['user_id'=>$orderQuery->user_id, 'ticket_id' => $orderQuery->coupon_id])->update(['state' => 1, 'update_date' => date('Y-m-d H:i:s')]);
                }
                // 更新订单状态为已支付，待发货
                DB::table('orders')->where(['batchcode' => $batchcode])->update(['payment_status'=> 1,'uniqueOrderNo'=> $callback['uniqueOrderNo'], 'status' => 2, 'pay_time' => date('Y-m-d H:i:s'), 'pay_code' => 0 ]);
                // 更新订单详情状态为已支付，待发货
                DB::table('orders_info')->where(['batchcode' => $batchcode])->update(['payment_status'=> 1,'status' => 2, 'pay_reatetime' => date('Y-m-d H:i:s'),'pay_batchode'=> $callback['uniqueOrderNo'], 'last_time' => date('Y-m-d H:i:s')]);

                $orderInfos = DB::table('orders_info')->where(['batchcode' => $batchcode])->get();
                foreach ($orderInfos as $orderInfo) {
                    // 更新每一件产品的状态为待发货
                    DB::table('product')->where(['id' => $orderInfo->product_id])->update(['product_state' => 10]);
                    // 如果商品是同步商品，则要发起分账请求并改变原商家订单的状态
                    YoppayService::updateOriginalOrder($orderInfo);
                }
                // 本商户提现金额里需要减去的金额（所有同步商品的同行价总和）
                $sholdRemoveMoney = 0;
                foreach ($orderInfos as $orderInfo) 
                {
                    $product = DB::table('product')->where(['id' => $orderInfo->product_id])->first();
                    if($product->is_synchro == 1)
                    {
                        $sourceProduct = DB::table('product')->where(['id' => $product->source_product_id])->first();
                        $sholdRemoveMoney = $sholdRemoveMoney + $sourceProduct->peer_price;
                    }
                }
                // 增加一条商户的不可提现余额记录
                DB::table('merchant_currency')->insert(['user_id'=>$orderQuery->business_id, 'orderId' => $orderQuery->id, 'money'=>round(($callback['payAmount']-$sholdRemoveMoney),2),'batchcode' =>$batchcode ,'uniqueOrderNo'=>$callback['uniqueOrderNo'] ,'type' => 1, 'state'=>0,'createtime'=>date('Y-m-d H:i:s')]);
               

                $order_status = DB::table('orders')->where(['batchcode' => $batchcode])->first();
            }

            if($order_status->payment_status == 1){
                    return 'SUCCESS';
                }else{
                    return DRS::returnError(1001,'支付失败');
                }
        }else{
            return DRS::returnError(1001,'支付失败');
        }
    }


    // 手动发送api请求分账（传订单号batchcode）
    public function merchant_divide(Request $request)
    { 
        $postData = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'batchcode' => 'required|string',
                                    ]);
        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }
        $batchcode = $postData['batchcode'];

        $orderInfos = DB::table('orders_info')->where(['batchcode' => $batchcode])->get();
        
        foreach ($orderInfos as $orderInfo) {
            // 更新每一件产品的状态为待发货
            DB::table('product')->where(['id' => $orderInfo->product_id])->update(['product_state' => 10]);

            // 如果商品是同步商品，则要发起分账请求并改变原商家订单的状态
            $return = YoppayService::updateOriginalOrder($orderInfo);
            if($return['code'] != 666){
                var_dump($return);exit(); 
            }
        }
    }
    public function pay_wechat(Request $request)
    {
        $postData  = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                        'business_id'   => 'required|numeric',
                                        'openid'        => 'required|string', 
                                        'batchcode'     => 'required',
                                        'total_fee'     => 'required|numeric',
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        $userInfo = Base::getUserByToken($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];

        $businessQuery = DB::table('business')->where(['business_id' => $postData['business_id']])->first();

        if($businessQuery !== null){
            $appid      = $businessQuery->appid;
            $mch_id     = $businessQuery->mch_id;
            $key        = $businessQuery->pay_key;
            if($appid == ''){
                return DRS::returnError(1001,'该商户未绑定公众号appid！');
            }elseif($mch_id == ''){
                return DRS::returnError(1001,'该商户未绑定微信支付商户号mch_id！');
            }elseif($key == ''){
                return DRS::returnError(1001,'该商户未绑定微信支付密钥key!');
            }else{
                $order = DB::table('orders')
                        ->where([
                                    'batchcode' => $postData['batchcode'], 
                                    'user_id' => $user['id'], 
                                    'state' => 0
                                ])
                        ->first();
                if($order == null){
                    $unitOrderValidate = WechatValidator::wexinPayUnitOrderValidate($postData['batchcode'], $user['id'], $postData['total_fee']);
                    if($unitOrderValidate['code'] != '666'){
                        return $unitOrderValidate;
                    }
                    $unitOrder = $unitOrderValidate['data'];
                    $out_trade_no = $unitOrder['pay_batchcode'];
                    $body = '芮享商品';
                    $weixinPayService = new WeixinPayService($appid, $postData['openid'], $mch_id, $key,$out_trade_no, $body, $postData['total_fee']);
                    $return = $weixinPayService->pay();
                    return $return;     
                    
                }else{
                    $orderValidate =  WechatValidator::wexinPayOrderValidate($order, $postData['total_fee']);
                    if($orderValidate['code'] != '666'){
                        return $orderValidate;
                    }
                    $out_trade_no = $order->batchcode;
                    $body = '芮享商品';
                    $weixinPayService = new WeixinPayService($appid, $postData['openid'], $mch_id, $key,$out_trade_no,$body,$postData['total_fee']);
                    $return = $weixinPayService->pay();
                    return $return;
                }
            }
        }else{
            return DRS::returnError(1001,'该商户不存在！', $businessQuery); 
        }


    }

    public function pay_notify_wechat()
    {
        $postData = WeixinPayService::post_data();
        
        if (empty($postData)) {
            return DRS::returnError(1001,'返回数据为空');
        }

        $post_data = WeixinPayService::xmlToArray($postData);

        $postSign = $post_data['sign'];
        unset($post_data['sign']);
        
        /* 微信官方提醒：
         *  商户系统对于支付结果通知的内容一定要做【签名验证】,
         *  并校验返回的【订单金额是否与商户侧的订单金额】一致，
         *  防止数据泄漏导致出现“假通知”，造成资金损失。
         */
        ksort($post_data);// 对数据进行排序

        $str = WeixinPayService::toUrlParams($post_data);//对数组数据拼接成key=value字符串

        $user_sign = strtoupper(md5($str));   //再次生成签名，与$postSign比较

        // if($user_sign !== $postSign){
        //     return DRS::returnError(1001,'签名不一致');
        // }
        $batchcode = $post_data['out_trade_no'];

        $orderQuery = DB::table('orders')->where(['batchcode' => $batchcode])->first();
        if($orderQuery == null){
            $unitOrder = DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->first();
            if($unitOrder == null){
                return DRS::returnError(1001,'找不到该订单');
            }else{
                $originOrder = DB::table('orders')->where(['batchcode' => $unitOrder->batchcode])->first();
                if($originOrder->coupon_id !== null){
                    DB::table('ticket_user')->where(['user_id'=>$originOrder->user_id, 'ticket_id' => $originOrder->coupon_id])->update(['state' => 1, 'update_date' => date('Y-m-d H:i:s')]);
                }
                DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->update(['payment_status'=> 1, 'payment_time' => date('Y-m-d H:i:s'), 'transaction_id' => $post_data['transaction_id'], 'pay_code' => 0, 'update_time' => date('Y-m-d H:i:s') ]);
                $unitOrders = DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->get();
                $is_allpay = true;
                foreach ($unitOrders as $key => $unitO) {
                    if($unitO->payment_status != 1){
                        $is_allpay = false;
                    }
                }
                if($is_allpay == true)
                {
                    DB::table('orders')->where(['batchcode' => $unitOrder->batchcode])->update(['payment_status'=> 1, 'status' => 2, 'pay_time' => date('Y-m-d H:i:s'), 'pay_code' => 0 ]);
                    DB::table('orders_info')->where(['batchcode' => $unitOrder->batchcode])->update(['payment_status'=> 1,'status' => 2, 'pay_reatetime' => date('Y-m-d H:i:s'), 'last_time' => date('Y-m-d H:i:s')]);
                    $orderInfos = DB::table('orders_info')->where(['batchcode' => $unitOrder->batchcode])->get();
                    foreach ($orderInfos as $orderInfo) {
                        DB::table('product')->where(['id' => $orderInfo->product_id])->update(['product_state' => 10]);
                    }
                }
                $order_status = DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->first();

            }
        }else{
            if($orderQuery->coupon_id !== null){
                DB::table('ticket_user')->where(['user_id'=>$orderQuery->user_id, 'ticket_id' => $orderQuery->coupon_id])->update(['state' => 1, 'update_date' => date('Y-m-d H:i:s')]);
            }
            DB::table('orders')->where(['batchcode' => $batchcode])->update(['payment_status'=> 1,'transaction_id'=> $post_data['transaction_id'], 'status' => 2, 'pay_time' => date('Y-m-d H:i:s'), 'pay_code' => 0 ]);
            DB::table('orders_info')->where(['batchcode' => $batchcode])->update(['payment_status'=> 1,'status' => 2, 'pay_reatetime' => date('Y-m-d H:i:s'), 'last_time' => date('Y-m-d H:i:s')]);
            $orderInfos = DB::table('orders_info')->where(['batchcode' => $batchcode])->get();
            foreach ($orderInfos as $orderInfo) {
                DB::table('product')->where(['id' => $orderInfo->product_id])->update(['product_state' => 10]);
            }
            DB::table('card_balance_log')->insertGetId(['user_id'=>$orderQuery->business_id,'']);
            $order_status = DB::table('orders')->where(['batchcode' => $batchcode])->first();
        }        
        
        if($post_data['return_code']=='SUCCESS'&&$postSign)
        {
            /*
            * 首先判断，订单是否已经更新为ok，因为微信会总共发送8次回调确认
            * 其次，订单已经为ok的，直接返回SUCCESS
            * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
            */
            if($order_status->payment_status == 1){
                return WeixinPayService::return_success();
            }else{
                return DRS::returnError(1001,'微信支付失败');
                // if($orderQuery == null){
                //     if( DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->update(['payment_status'=> 1, 'payment_time' => date('Y-m-d H:i:s'),'pay_code' => 0,'transaction_id' => $post_data['transaction_id'], 'update_time' => date('Y-m-d H:i:s') ])
                //     ){
                //         return WeixinPayService::return_success();
                //     }
                // }else{
                //     if(
                //         DB::table('orders')->where(['batchcode' => $batchcode])->update(['payment_status'=> 1, 'status' => 2, 'pay_time' => date('Y-m-d H:i:s'), 'transaction_id' => $post_data['transaction_id'], 'pay_code' => 0 ])
                //     ){
                //         return WeixinPayService::return_success();
                //     }
                // }
            }
        }else{
            return DRS::returnError(1001,'微信支付失败');
        }
    }

}